
# Create your views here.
"""登录"""
from django.http import HttpResponseRedirect
from django.shortcuts import render, redirect
from django.contrib.auth import authenticate, login, logout
from django.urls import reverse
from django.contrib import messages
from typing import TypedDict
from django.http.request import HttpRequest
from django.views.decorators.csrf import csrf_exempt

class UserLogin(TypedDict):
    username: str
    password: str

@csrf_exempt
def login_view(request: HttpRequest) -> HttpResponseRedirect:
    if request.method == 'POST':
        data: UserLogin = request.POST
        username = data.get('username')
        password = data.get('password')
        user = authenticate(request, username=username, password=password)
        if user is not None and user.is_active:
            login(request, user)
            next_url = request.GET.get('next')
            if next_url and request.is_safe_url(next_url, allowed_hosts={request.get_host()}):
                return HttpResponseRedirect(next_url)
            else:
                return redirect(reverse('home'))
        else:
            messages.error(request, "用户名或密码错误")  # 添加错误信息
            return render(request, 'login.html', {'messages': messages.get_messages(request)})  # 将消息传递给模板
    return render(request, 'login.html', {'messages': messages.get_messages(request)})  # 首次访问也传递消息

def logout_view(request):
    logout(request)
    return redirect('login')


